package com.education.platform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.education.platform.common.ResultCode;
import com.education.platform.dto.category.CategoryCreateDTO;
import com.education.platform.entity.Category;
import com.education.platform.exception.BusinessException;
import com.education.platform.mapper.CategoryMapper;
import com.education.platform.service.CategoryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 分类服务实现类
 *
 * @author education-platform
 * @since 2024-09-27
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class CategoryServiceImpl implements CategoryService {

    private final CategoryMapper categoryMapper;

    @Override
    @Transactional
    public Long createCategory(CategoryCreateDTO categoryCreateDTO) {
        Category category = new Category();
        BeanUtil.copyProperties(categoryCreateDTO, category);

        if (category.getParentId() == null) {
            category.setParentId(0L);
        }

        if (category.getSort() == null) {
            category.setSort(0);
        }

        category.setStatus(Category.Status.ACTIVE.name());
        categoryMapper.insert(category);
        return category.getId();
    }

    @Override
    @Transactional
    public void updateCategory(Long id, CategoryCreateDTO categoryCreateDTO) {
        Category category = getCategoryById(id);
        BeanUtil.copyProperties(categoryCreateDTO, category, "id");
        categoryMapper.updateById(category);
    }

    @Override
    @Transactional
    public void deleteCategory(Long id) {
        // 检查是否有子分类
        Integer childCount = categoryMapper.countByParentId(id);
        if (childCount > 0) {
            throw new BusinessException(ResultCode.SYSTEM_ERROR);
        }
        categoryMapper.deleteById(id);
    }

    @Override
    public Category getCategoryById(Long id) {
        Category category = categoryMapper.selectById(id);
        if (category == null) {
            throw new BusinessException(ResultCode.NOT_FOUND);
        }
        return category;
    }

    @Override
    public List<Category> getCategoryTree() {
        return categoryMapper.selectCategoryTree();
    }

    @Override
    public List<Category> getChildCategories(Long parentId) {
        return categoryMapper.selectByParentId(parentId);
    }

    @Override
    @Transactional
    public void updateStatus(Long id, String status) {
        Category category = getCategoryById(id);
        category.setStatus(status);
        categoryMapper.updateById(category);
    }

    @Override
    public List<Category> getActiveCategories() {
        return categoryMapper.selectActiveCategories();
    }
}

